package cn.fl.warrant.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.fl.commons.result.ResponseData;
import cn.fl.preloan.IInsPlcBscInfoService;
import cn.fl.preloan.condition.InsPlcBscInfoQueryCondition;
import cn.fl.preloan.dto.insurance.GetInsPlcBscInfoListRequest;
import cn.fl.preloan.dto.insurance.InsPlcBscInfoDTO;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.dto.SysOrgDTO;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.capital.service.ICapPayInfoApiService;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.preloan.condition.PrjPrdInvoiceQueryCondition;
import cn.fl.project.api.IProjectQueryApiService;
import cn.fl.project.condition.PrjBscInfoQueryCondition;
import cn.fl.project.condition.PrjContCfgDQC;
import cn.fl.project.condition.PrjPrdDtlForInsQueryCondition;
import cn.fl.project.constant.PrjPrdMtgConstant;
import cn.fl.project.dto.PrjContCfgDDTO;
import cn.fl.project.dto.PrjPrdDtlForInsDTO;
import cn.fl.project.dto.PrjPrdSourceInfoDTO;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjPrdInvoiceService;
import cn.fl.project.service.IPrjPrdMtgService;
import cn.fl.project.service.IPrjPrdPaySchMApiService;
import cn.fl.project.service.IProjectApiService;
import cn.fl.project.vo.PrjBscInfoVO;
import cn.fl.project.vo.PrjPrdInvoiceVO;
import cn.fl.project.vo.PrjPrdMtgVO;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.vo.SysUlFilesRecVO;
import cn.fl.warrant.service.IArcBscInfoService;
import cn.fl.warrant.service.IArcMgrMainService;
import cn.fl.warrant.service.IArcReceiptMainService;
import cn.fl.warrant.transform.ArcApplyDetailVOTransform;
import cn.fl.warrant.transform.ArcApplyMainVOTransform;
import cn.fl.warrant.transform.ArcMgrDetailVOTransform;
import cn.fl.warrant.transform.ArcMgrMainVOTransform;
import cn.fl.warrant.transform.ArcReceiptDetailVOTransform;
import cn.fl.warrant.vo.ArcApplyDetailVO;
import cn.fl.warrant.vo.ArcApplyMainVO;
import cn.fl.warrant.vo.ArcBscInfoVO;
import cn.fl.warrant.vo.ArcMgrDetailVO;
import cn.fl.warrant.vo.ArcMgrMainVO;
import cn.fl.warrant.vo.ArcReceiptDetailVO;
import fl.ref.fribaseinfo.condition.FriBaseInfoQueryCondition;
import fl.ref.fribaseinfo.dto.FriBaseInfoDTO;
import fl.ref.fribaseinfo.service.IFriBaseInfoApiService;
import fl.riskctrl.facade.riskctrl.api.IRiskCtrlSearchApiService;
import fl.warrant.facade.archive.api.IArcApplyDetailApiService;
import fl.warrant.facade.archive.api.IArcApplyMainApiService;
import fl.warrant.facade.archive.api.IArcMgrDetailApiService;
import fl.warrant.facade.archive.api.IArcMgrMainApiService;
import fl.warrant.facade.archive.condition.ArcMgrDetailQC;
import fl.warrant.facade.archive.condition.ArcMgrMainQC;
import fl.warrant.facade.archive.condition.ArcReceiptDetailQueryCondition;
import fl.warrant.facade.archive.constant.ArchiveConstants;
import fl.warrant.facade.archive.dto.ArcMgrDetailDTO;
import fl.warrant.facade.archive.dto.ArcMgrMainDTO;
import tc.esign.facade.esign.api.IFilSignApiService;
import tc.esign.facade.esign.condition.FilSignQueryCondition;
import tc.esign.facade.esign.dto.FilSignDTO;

/**
 * @Description: 档案管理主表(旧表：T_API_DOCUMENT_RENTPLAN) 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get*
 *               批量：batch* 查询集合：search*
 */
@Service
public class ArcMgrMainServiceImpl implements IArcMgrMainService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(IArcMgrMainService.class);

	/**
	 * TODO 自定义 API 暴露服务
	 */
	@Autowired
	private IArcMgrMainApiService arcMgrMainApiService;
	@Autowired
	private IArcMgrDetailApiService arcMgrDetailApiService;
//	@Autowired
//	private IProjectApiService projectApiService;
	@Autowired
	private IPrjBscInfoService prjBscInfoService;
	@Autowired
	private ICapPayInfoApiService capPayInfoApiService;
	@Autowired
	private IPrjPrdPaySchMApiService prjPrdPaySchMApiService;
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	@Autowired
	private ISysOrgApiService sysOrgApiService;// 组织机构
	@Autowired
	private ICstBscInfoService cstBscInfoService;
	@Autowired
	private IArcApplyMainApiService arcApplyMainApiService;
	@Autowired
	private IArcApplyDetailApiService arcApplyDetailApiService;
	@Autowired
	private IFilSignApiService filSignApiService;
	@Autowired
	private IFriBaseInfoApiService friBaseInfoApiService;
	@Autowired
	private ISysUlFilesRecService sysUlFilesRecService;
	@Autowired
	private IInsPlcBscInfoService insPlcBscInfoService;
	@Autowired
	private IPrjPrdMtgService prjPrdMtgService;
	@Autowired
	private IProjectQueryApiService projectQueryApiService;
	@Autowired
	private IRiskCtrlSearchApiService riskCtrlSearchApiService;
	@Autowired
	private IPrjPrdInvoiceService prjPrdInvoiceService;
	@Autowired
	private IArcBscInfoService arcBscInfoService;
	@Autowired
	private IArcReceiptMainService arcReceiptMainService;
	@Autowired
	private IProjectApiService projectApiService;
	
	@Override
	public ArcMgrMainVO selectById(Long id) throws BaseException {
		if (StringUtils.isEmpty(id)) {
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		// TODO 业务逻辑
		ArcMgrMainDTO dto = arcMgrMainApiService.selectById(id);
		ArcMgrMainVO vo = ArcMgrMainVOTransform.toVO(dto);
		if (vo != null && vo.getId() != null) {
			ArcMgrDetailQC dQc = new ArcMgrDetailQC();
			dQc.setArcMgrMainId(vo.getId());
			String sysCd = CurrentThreadContext.getCurrentSysCd();
			String orgCd = CurrentThreadContext.getCurrentOrgCd();
			List<ArcMgrDetailDTO> list = arcMgrDetailApiService.searchList(dQc, sysCd, orgCd);

			vo.setArcMgrDetailList(ArcMgrDetailVOTransform.toVOList(list));
		}
		return vo;
	}

	@Override
	public ArcMgrMainVO selectByContractNo(String contractNo) throws BaseException {
		if (StringUtils.isEmpty(contractNo)) {
			BaseLogUtils.info(logger, "selectByContractNo", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		// TODO 业务逻辑
		ArcMgrMainDTO dto = this.arcMgrMainApiService.selectByContractNo(contractNo);
		ArcMgrMainVO vo = ArcMgrMainVOTransform.toVO(dto);
		if (vo != null && vo.getId() != null) {
			ArcMgrDetailQC dQc = new ArcMgrDetailQC();
			dQc.setArcMgrMainId(vo.getId());
			String sysCd = CurrentThreadContext.getCurrentSysCd();
			String orgCd = CurrentThreadContext.getCurrentOrgCd();
			List<ArcMgrDetailDTO> list = this.arcMgrDetailApiService.searchList(dQc, sysCd, orgCd);
			List<ArcMgrDetailVO> list1 = ArcMgrDetailVOTransform.toVOList(list);
			// 合同电子赋值
			this.getFilSign(list1);
			// 获取附件
			this.getFiles(list1);
			vo.setArcMgrDetailList(list1);
		}
		return vo;
	}

	@Override
	public Long add(ArcMgrMainVO entity) throws BaseException {
		if (null == entity) {
			BaseLogUtils.info(logger, "add", "新增对象不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		Long id = this.arcMgrMainApiService.add(ArcMgrMainVOTransform.toDTO(entity));
		if (entity.getArcMgrDetailList() != null) {
			for (int i = 0; i < entity.getArcMgrDetailList().size(); i++) {
				ArcMgrDetailVO vo = entity.getArcMgrDetailList().get(i);
				vo.setPaylistCode(entity.getPaySchNo());
				vo.setArcMgrMainId(id);
				// vo.setEleId(null);
				this.arcMgrDetailApiService.add(ArcMgrDetailVOTransform.toDTO(vo));
			}
		}
		return id;

	}

	@Override
	public boolean removeById(Long id) throws BaseException {
		if (StringUtils.isEmpty(id)) {
			BaseLogUtils.info(logger, "removeById", "删除主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		return this.arcMgrMainApiService.removeById(id);
		// TODO 业务逻辑
		// return false;
	}

	/**
	 * 删除
	 * 
	 * @param ids
	 * @return
	 */
	public boolean removeByIds(List<Long> ids) throws BaseException {
		if (CollectionUtils.isEmpty(ids)) {
			BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		;
		return false;
	}

	@Override
	public boolean modify(ArcMgrMainVO entity) throws BaseException {
		if (null == entity) {
			BaseLogUtils.info(logger, "modify", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		boolean flag = this.arcMgrMainApiService.modify(ArcMgrMainVOTransform.toDTO(entity));
		if (entity.getArcMgrDetailList() != null) {
			for (int i = 0; i < entity.getArcMgrDetailList().size(); i++) {
				ArcMgrDetailVO vo = entity.getArcMgrDetailList().get(i);
				this.arcMgrDetailApiService.modify(ArcMgrDetailVOTransform.toDTO(vo));
			}
		}
		// return this.arcMgrMainApiService.modify(ArcMgrMainVOTransform.toDTO(entity));
		// TODO 业务逻辑
		return flag;
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException {
		if (null == page)
			page = new Pager();

		page = this.arcMgrMainApiService.searchListPage(page);

		return page;

	}

	@Override
	public Pager selectListForListPage(Pager page) throws BaseException {
		if (null == page)
			page = new Pager();
		page = this.arcMgrMainApiService.selectListForListPage(page, CurrentThreadContext.getCurrentSysCd(),
				CurrentThreadContext.getCurrentOrgCd());
		List<ArcMgrMainVO> list = ArcMgrMainVOTransform.toVOList((List<ArcMgrMainDTO>) page.getResultList());
//		if (list!=null&&list.size()>0) {
//			List<Long> paySchIdList =new ArrayList<Long>();
//			for (ArcMgrMainVO vo:list) {
//				paySchIdList.add(vo.getPaySchId());
//			}
//			//查询租赁物信息
//			BaseParamDTO baseParamDTO = new BaseParamDTO();
//			PrjPrdDtlQueryCondition dtlQc=new PrjPrdDtlQueryCondition();
//			dtlQc.setPaySchIdList(paySchIdList);
//			
//			baseParamDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
//			baseParamDTO.setChannelCd(WebBaseConstant.CHANNEL_CD);
//            baseParamDTO.setFrontCd(PropertiesCacheUtils.getProperty(WebBaseConstant.FL_SERVICE_SYS_CD));
//            baseParamDTO.setServiceCd(PropertiesCacheUtils.getProperty(WebBaseConstant.FL_SERVICE_SYS_CD));
//			List<PrjPrdDtlDTO> dtlList= this.projectSpecialApiService.searchPrjPrdDtlDTOList(dtlQc, baseParamDTO);
//			for (ArcMgrMainVO vo:list) {
//				for (PrjPrdDtlDTO dtl: dtlList) {
//					if (dtl.getPaySchNo().equals(vo.getPaySchNo())) {
//						vo.setDtl(dtl);
//					}
//				}
//			}		
//		}
		page.setResultList(list);
		return page;

	}

	@Override
	public List<KeyValueVO> getStorageStatusList() throws BaseException {
		return this.sysDictionaryApiService.getKvList(ArchiveConstants.ARC002, CurrentThreadContext.getCurrentSysCd(),
				CurrentThreadContext.getCurrentOrgCd());
	}

	@Override
	public List<KeyValueVO> getPrList() throws BaseException {

		List<SysOrgDTO> list = this.sysOrgApiService.searchSysOrgListBy(CurrentThreadContext.getCurrentSysCd());
		List<KeyValueVO> sorgList = new ArrayList<KeyValueVO>();
		if (CollectionUtils.isNotEmpty(list)) {
			for (SysOrgDTO sysOrgDTO : list) {
				if ("3".equals(sysOrgDTO.getOrgTypCd())) {
					KeyValueVO keyValueVO = new KeyValueVO();
					keyValueVO.setKey(sysOrgDTO.getOrgCd());
					keyValueVO.setValue(sysOrgDTO.getOrgDispNm());
					sorgList.add(keyValueVO);
				}
			}
		}
		return sorgList;
	}

	/**
	 * 设置筛选条件
	 * 
	 * @param request 2018年2月27日 lxb
	 */
	@Override
	public void setAttribute(HttpServletRequest request) {
		String syscd = CurrentThreadContext.getCurrentSysCd();
		String orgcd = CurrentThreadContext.getCurrentOrgCd();
		request.setAttribute("lesseeTypeList",
				this.sysDictionaryApiService.getKvList(DictionaryConstant.CODE_GRP_CST_TYP_CD, syscd, orgcd));// 承租人类型(客户类型)
		request.setAttribute("contractSignList",
				this.sysDictionaryApiService.getKvList(DictionaryConstant.CODE_CNT_TYP_CD, syscd, orgcd));// 合同签署方式
		request.setAttribute("buOrgCdList", this.cstBscInfoService.searchBusinessOrgList());// 事业部
		request.setAttribute("prjBizTypeList",
				this.sysDictionaryApiService.getKvList(DictionaryConstant.CODE_PRJ_BIZ_TYP_CD, syscd, orgcd));// 业务类型
		request.setAttribute("settleTypeList",
				this.sysDictionaryApiService.getKvList(DictionaryConstant.CODE_PRJ_PRD_STS_CD, syscd, orgcd));// 结清类型（支付表状态）
		request.setAttribute("guaranteeList",
				this.sysDictionaryApiService.getKvList(ArchiveConstants.ARC_GUARANTEE, syscd, orgcd));// 担保人
		request.setAttribute("guaranteeTypeList",
				this.sysDictionaryApiService.getKvList(ArchiveConstants.ARC_GUARANTEE_TYPE, syscd, orgcd));// 担保人类型
		request.setAttribute("sendTypeList",
				this.sysDictionaryApiService.getKvList(ArchiveConstants.ARC010, syscd, orgcd));// 接收方式
		request.setAttribute("sendCompanyList",
				this.sysDictionaryApiService.getKvList(ArchiveConstants.ARC012, syscd, orgcd));// 邮递公司
		request.setAttribute("projectTypeList", this.prjBscInfoService.getPrjTypCdALLKV());// 项目类型
		request.setAttribute("payWayCdList",
				this.sysDictionaryApiService.getKvList("MFR0001", syscd, orgcd));// 厂商放款方式
		FriBaseInfoQueryCondition condition = new FriBaseInfoQueryCondition();
		condition.setInsUseCd("2");// 只查询资管类型的融资机构
		List<FriBaseInfoDTO> friBaseInfoDTOList = friBaseInfoApiService.searchList(condition);
		request.setAttribute("friBaseInfoDTOList", friBaseInfoDTOList);// 融资机构(资管)
	}

	@Override
	public List<ArcMgrMainVO> viewDetail(ArcMgrMainQC qc) throws BaseException {
		// TODO Auto-generated method stub
		String sysCd = CurrentThreadContext.getCurrentSysCd();
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		Pager pager = new Pager();
		pager.setCurrentPage(0);
		pager.setEveryPage(10000);
		pager.setCondition(qc);
		List<ArcMgrMainVO> voList = (List<ArcMgrMainVO>) this.selectListForListPage(pager).getResultList();
		if (voList != null) {
			for (int i = 0; i < voList.size(); i++) {
				ArcMgrMainVO vo = voList.get(i);
				if (vo.getId() != null) {

					ArcMgrDetailQC dQc = new ArcMgrDetailQC();
					dQc.setArcMgrMainId(vo.getId());
					List<ArcMgrDetailVO> list = ArcMgrDetailVOTransform
							.toVOList(arcMgrDetailApiService.searchList(dQc, sysCd, orgCd));
					// 合同电子赋值
					this.getFilSign(list);
					// 获取附件
					this.getFiles(list);
					vo.setArcMgrDetailList(list);
				}

			}
		}

		return voList;
	}

	@Override
	public Long addApply(ArcMgrMainVO entity, Map map) throws BaseException {
		if (null == entity) {
			BaseLogUtils.info(logger, "add", "新增对象不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		ArcApplyMainVO aentity = ArcApplyMainVOTransform.mgrToVO(entity);
		aentity.setIsDel(0);// 是否删除（1：是，0：否）
		// 如果是有归档中的则标识
//		if ("2".equals(entity.getStorageStatus())) {
//			aentity.setIsValid(-1);
//		}
		Long id = this.arcApplyMainApiService.add(ArcApplyMainVOTransform.toDTO(aentity));
		// 保存合同档案
		if (entity.getArcMgrDetailList() != null) {
			for (int i = 0; i < entity.getArcMgrDetailList().size(); i++) {
				ArcMgrDetailVO vo = entity.getArcMgrDetailList().get(i);
				ArcApplyDetailVO avo = ArcApplyDetailVOTransform.mgrToVO(vo);
				avo.setArcApplyMainId(id);

				this.arcApplyDetailApiService.add(ArcApplyDetailVOTransform.toDTO(avo));
			}

		}
		// 保存支付表档案
		if (map.get("mgrList") != null) {
			List<ArcMgrMainVO> mgrList = (List<ArcMgrMainVO>) map.get("mgrList");
			for (int i = 0; i < mgrList.size(); i++) {
				ArcMgrMainVO mvo = mgrList.get(i);
				// TODO ADD PARAM
				if (mvo.getArcMgrDetailList() != null) {
					for (int j = 0; j < mvo.getArcMgrDetailList().size(); j++) {
						ArcMgrDetailVO vo = mvo.getArcMgrDetailList().get(j);
						ArcApplyDetailVO avo = ArcApplyDetailVOTransform.mgrToVO(vo);
						avo.setArcApplyMainId(id);
						avo.setPaylistCode(mvo.getPaySchNo());

						this.arcApplyDetailApiService.add(ArcApplyDetailVOTransform.toDTO(avo));
					}

				}
			}
		}
		return id;
	}

	/**
	 * 档案管理主表查询
	 */
	@Override
	public List<ArcMgrMainVO> selectList(ArcMgrMainQC qc) throws BaseException {
		return ArcMgrMainVOTransform.toVOList(arcMgrMainApiService.selectList(qc));
	}

	/**
	 * 根据档案管理主表更新档案管理移交状态
	 */
	@Override
	public boolean updateById(ArcMgrMainVO entity) throws BaseException {
		if (null == entity) {
			BaseLogUtils.info(logger, "updateById", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		boolean flag = this.arcMgrMainApiService.updateById(ArcMgrMainVOTransform.toDTO(entity));
		return flag;
	}

	/**
	 * 合同电子赋值
	 * 
	 * 2018年12月11日 lxb
	 */
	@Override
	public void getFilSign(List<ArcMgrDetailVO> list) {
		try {
			// 合同电子赋值
			for (ArcMgrDetailVO dvo : list) {
				if (ArchiveConstants.DOSSOER_TEMP_3.equals(dvo.getDossierTemp()) && dvo.getEleId() != null) {
					FilSignQueryCondition qc3 = new FilSignQueryCondition();
					qc3.setId(dvo.getEleId());
					List<FilSignDTO> list2 = this.filSignApiService.getListFilSignByQc(qc3);
					if (list2 != null && list2.size() > 0) {
						dvo.setEleId(list2.get(0).getId());
						dvo.setFilePath(list2.get(0).getFilePath());
					}
				}

			}
		} catch (Exception e) {
			// TODO: handle exception
			BaseLogUtils.error(logger, "getFilSign", e.getMessage());
		}
	}

	/**
	 * 获取附件
	 */
	@Override
	public void getFiles(List<ArcMgrDetailVO> list) {
		try {
			if (list == null || list.size() < 1) {
				return;
			}
			// 获取项目id，支付表id，产品id，客户id
			PrjPrdDtlForInsQueryCondition con = new PrjPrdDtlForInsQueryCondition();
			con.setLsCntNo(list.get(0).getContractNo());
			con.setSysCd(CurrentThreadContext.getCurrentSysCd());
			con.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			List<PrjPrdDtlForInsDTO> list2 = this.prjPrdPaySchMApiService.searchInsurePrdList(con);
			if (list2 != null) {
				for (PrjPrdDtlForInsDTO mdto : list2) {
					if (mdto.getLsCntNo() != null && mdto.getLsCntNo().equals(list.get(0).getContractNo())) {

						for (ArcMgrDetailVO dvo : list) {
							List<SysUlFilesRecVO> liStrings = new ArrayList<SysUlFilesRecVO>();
							// 承租人(权证类别2)-身份证-客户id
							if ("2".equals(dvo.getFileFlag()) && dvo.getFileName().contains("身份证")) {
								dvo.setUlFlag("1");
								// 获取文件列表
								SysUlFilesRecQueryCondition qc3 = new SysUlFilesRecQueryCondition();
								qc3.setPkId(mdto.getCstId().toString());
								qc3.setSysCd(CurrentThreadContext.getCurrentSysCd());
								List<SysUlFilesRecVO> files = sysUlFilesRecService.searchList(qc3);
								// 匹配配置码
								String[] ids = ArchiveConstants.DZ_IDCARD.split("_");
								for (SysUlFilesRecVO file : files) {
									for (int i = 0; i < ids.length;) {
										if (ids[i].equals(file.getCfgCd()) && ids[i + 1].equals(file.getCfgDtlCd())) {
											liStrings.add(file);
										}
										i = i + 2;
									}
								}
								dvo.setUlFiles(liStrings);
								if (liStrings.size() > 0) {
									dvo.setEleId(1L);
								}
								// 权证资料-商业险-通过支付表id找INS_PLC_BSC_INFO的id。
							} else if (dvo.getFileName().contains("商业险")) {
								dvo.setUlFlag("1");
								// 获取文件列表
								if (StringUtils.isNotBlank(dvo.getPaylistCode())) {
									// 查找保险id
									InsPlcBscInfoQueryCondition condition = new InsPlcBscInfoQueryCondition();
									condition.setInsTypCd("1");
									condition.setPaySchNo(dvo.getPaylistCode());
									condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
									condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
									GetInsPlcBscInfoListRequest getListRequest = new GetInsPlcBscInfoListRequest(condition);
									getListRequest.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
									getListRequest.setSysCd(CurrentThreadContext.getCurrentSysCd());
									BaseLogUtils.info(logger, "searchList", "贷前--获取保单数据，request:" + JSONObject.toJSONString(getListRequest), CurrentThreadContext.getCurrentUserName());
									ResponseData<List<InsPlcBscInfoDTO>> infoResponse = insPlcBscInfoService.searchList(getListRequest);
									BaseLogUtils.info(logger, "searchList", "贷前--获取保单数据,response:" + JSONObject.toJSONString(infoResponse), CurrentThreadContext.getCurrentUserName());
									if (null != infoResponse && ResponseData.SUCCESS_CODE.equals(infoResponse.getCode()) && CollectionUtils.isNotEmpty(infoResponse.getData())){
										for (InsPlcBscInfoDTO ins : infoResponse.getData()) {
											if (ins.getPaySchNo() != null
													&& ins.getPaySchNo().equals(dvo.getPaylistCode())) {
												// 获取文件列表
												SysUlFilesRecQueryCondition qc3 = new SysUlFilesRecQueryCondition();
												qc3.setPkId(ins.getId().toString());
												qc3.setTabNm("INS_PLC_BSC_INFO");
												qc3.setSysCd(CurrentThreadContext.getCurrentSysCd());
												List<SysUlFilesRecVO> files = sysUlFilesRecService.searchList(qc3);
												// 匹配配置码
												String[] ids = ArchiveConstants.DZ_SYX.split("_");
												for (SysUlFilesRecVO file : files) {
													for (int i = 0; i < ids.length;) {
														if (ids[i].equals(file.getCfgCd())
																&& ids[i + 1].equals(file.getCfgDtlCd())) {
															liStrings.add(file);
														}
														i = i + 2;
													}
												}

											}
										}
									}
								}
								dvo.setUlFiles(liStrings);
								if (liStrings.size() > 0) {
									dvo.setEleId(1L);
								}
								// 权证资料-设备销售发票-prj_prd_dtl
							} else if (dvo.getFileName().contains("设备销售发票")) {
								dvo.setUlFlag("1");
								//通过设备id找
								for (PrjPrdDtlForInsDTO m : list2) {
									if (dvo.getPaylistCode() != null && dvo.getPaylistCode().equals(m.getPaySchNo())) {
										// 获取文件列表
										SysUlFilesRecQueryCondition qc3 = new SysUlFilesRecQueryCondition();
										qc3.setPkId(m.getPrjPrdDtlId().toString());
										qc3.setTabNm("PRJ_PRD_DTL");
										qc3.setSysCd(CurrentThreadContext.getCurrentSysCd());
										List<SysUlFilesRecVO> files = sysUlFilesRecService.searchList(qc3);
										// 匹配配置码
										String[] ids = null;
										//if (m.getCstMgrOrgCd() != null
										//		&& "000000080002".equals(m.getCstMgrOrgCd().substring(0, 12))) {
										//	ids = ArchiveConstants.DZ_FAPIAO_ZC.split("_");
										//} else {
											ids = ArchiveConstants.DZ_FAPIAO.split("_");
										//}
										for (SysUlFilesRecVO file : files) {
											for (int i = 0; i < ids.length;) {
												if (ids[i].equals(file.getCfgCd())
														&& ids[i + 1].equals(file.getCfgDtlCd())) {
													liStrings.add(file);
												}
												i = i + 2;
											}
										}
										break;
									}

								}
								//通过发票id找
									if (dvo.getPaylistCode() != null ) {
										PrjPrdInvoiceQueryCondition condition=new PrjPrdInvoiceQueryCondition();
										condition.setPaySchNo(dvo.getPaylistCode());
//										List<PrjPrdInvoiceDTO> invoiceList=this.projectApiService.searchPrjPrdInvoiceList(condition);
										List<PrjPrdInvoiceVO> invoiceList = prjPrdInvoiceService.searchPrjPrdInvoiceList(condition);
										for (PrjPrdInvoiceVO m : invoiceList) {
											if ( dvo.getPaylistCode().equals(m.getPaySchNo())) {
												// 获取文件列表
												SysUlFilesRecQueryCondition qc3 = new SysUlFilesRecQueryCondition();
												qc3.setPkId(m.getId().toString());
												qc3.setTabNm("PRJ_PRD_INVOICE");
												qc3.setSysCd(CurrentThreadContext.getCurrentSysCd());
												List<SysUlFilesRecVO> files = sysUlFilesRecService.searchList(qc3);
												// 匹配配置码
												String[] ids = null;
												ids = ArchiveConstants.DZ_FAPIAO.split("_");
												
												for (SysUlFilesRecVO file : files) {
													for (int i = 0; i < ids.length;) {
														if (ids[i].equals(file.getCfgCd())
																&& ids[i + 1].equals(file.getCfgDtlCd())) {
															liStrings.add(file);
														}
														i = i + 2;
													}
												}
												
											}
										}
									}

								dvo.setUlFiles(liStrings);
								if (liStrings.size() > 0) {
									dvo.setEleId(1L);
								}
							} else if (dvo.getFileName().contains(ArchiveConstants.VE_NAME_X2)) {// 权证资料登记证车辆信息页2
								dvo.setUlFlag("1");
								for (PrjPrdDtlForInsDTO m : list2) {
									if (dvo.getPaylistCode() != null && dvo.getPaylistCode().equals(m.getPaySchNo())) {
										SysUlFilesRecQueryCondition qc = new SysUlFilesRecQueryCondition();
										qc.setPkId(m.getPrjPrdDtlId().toString());
										qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
										List<SysUlFilesRecVO> files = sysUlFilesRecService.searchList(qc);
										String[] ids = ArchiveConstants.DZ_CERT_REG_CAR.split("_");
										for (SysUlFilesRecVO file : files) {
											for (int i = 0; i < ids.length;) {
												if (ids[i].equals(file.getCfgCd())
														&& ids[i + 1].equals(file.getCfgDtlCd())) {
													// 信审验证通过（抵押为通过状态），才能显示
													//if (checkMgtState(m.getPrjPrdDtlId())) {
														liStrings.add(file);
													//}
												}
												i = i + 2;
											}
										}
										break;
									}

								}
								dvo.setUlFiles(liStrings);
								if (liStrings.size() > 0) {
									dvo.setEleId(1L);
								}
							} else if (dvo.getFileName().contains(ArchiveConstants.VE_NAME2)) {// 权证资料 登记证抵押我司页2 
								dvo.setUlFlag("1");
								for (PrjPrdDtlForInsDTO m : list2) {
									if (dvo.getPaylistCode() != null && dvo.getPaylistCode().equals(m.getPaySchNo())) {
										// 获取文件列表
										SysUlFilesRecQueryCondition qc = new SysUlFilesRecQueryCondition();
										qc.setPkId(m.getPrjPrdDtlId().toString());
										qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
										List<SysUlFilesRecVO> files = sysUlFilesRecService.searchList(qc);
										String[] ids = ArchiveConstants.DZ_CERT_REG_MGT.split("_");
										boolean flagString=false;
										for (SysUlFilesRecVO file : files) {
											for (int i = 0; i < ids.length;) {
												if (ids[i].equals(file.getCfgCd())
														&& ids[i + 1].equals(file.getCfgDtlCd())) {
													// 信审验证通过（抵押为通过状态），才能显示
													if (checkMgtState(m.getPrjPrdDtlId())) {
														liStrings.add(file);
													}
													  String relStr;//抵押验证结果
										              String fileRem = file.getFileRem();//上传附件备注
										              if(StringUtils.isBlank(fileRem)) {
										               relStr = "未验证";
										              }else if(fileRem.equals("1")) {
										               relStr = "验证通过";
										               flagString=true;
										              }else {
										               relStr = "验证不通过 ";
										               String[] fileRemArray = fileRem.split("\\|");
										               if(fileRemArray.length ==2) {
										                   relStr = relStr + " 原因：" + fileRemArray[1];
										               }
										              }
										             dvo.setBz(relStr);
										             
												}
												i = i + 2;
											}
											if(flagString) {											               
									               break;
									        }
										}
										break;
									}

								}
								dvo.setUlFiles(liStrings);
								if (liStrings.size() > 0) {
									dvo.setEleId(1L);
								}
								
							} else if (dvo.getFileName().contains("二手车车辆检测报告")) {//二手车车辆检测报告prj_prd_source_info表PDF_FILE_PATH
								dvo.setUlFlag("1");
								for (PrjPrdDtlForInsDTO m : list2) {
									if (dvo.getContractNo() != null && dvo.getContractNo().equals(m.getLsCntNo())) {
										PrjPrdSourceInfoDTO ps= projectApiService.selectPrjPrdSourceInfoById(m.getPrjPrdId());
										if (ps != null && ps.getPdfFilePath() != null){
											String pdfFilepath = PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_SERVER_PATH)+ps.getPdfFilePath();
											SysUlFilesRecVO file=new SysUlFilesRecVO();
											file.setFilePath(pdfFilepath);
											liStrings.add(file);
										}
										
									}

								}
								dvo.setUlFiles(liStrings);
								if (liStrings.size() > 0) {
									dvo.setEleId(1L);
								}
							}
						}
						break;
					}
				}
			}
		} catch (Exception e) {
			//e.printStackTrace();
			BaseLogUtils.error(logger, "getFiles", e.getMessage());
		}
	}

	private boolean checkMgtState(Long prjPrdDtlId) {
		boolean flag = false;
		if (prjPrdDtlId != null) {
			PrjPrdMtgVO prjPrdMtgVO = this.prjPrdMtgService.selectById(prjPrdDtlId);
			if (prjPrdMtgVO != null && PrjPrdMtgConstant.CODE_GUAR_STS_CD_MTG.equals(prjPrdMtgVO.getGuarStsCd())) {
				flag = true;
			}
		}
		return flag;
	}
	/**
	 * 电子合同赋值
	 * 
	 * 2020年8月11日 
	 * lxb
	 */
	@Override
	public void setFilSign(List<ArcMgrMainVO> mgrList,ArcMgrMainVO cVo) {
		//已经存在的不用再查询，map放不存在的
		//合同电子赋值
		Map<Long,String> hMap=new HashMap<Long,String>();
		if(cVo.getArcMgrDetailList()!=null) {
			for (ArcMgrDetailVO dvo:cVo.getArcMgrDetailList()) {
					if (ArchiveConstants.DOSSOER_TEMP_3.equals(dvo.getDossierTemp())
							&&(dvo.getEleId()==null||dvo.getEleId()<1)) {
						hMap.put(dvo.getArcReceiptDetailId(),"1");
					}
			}
		}else {
			return;
		}		
		for (int i = 0; i < mgrList.size(); i++) {
			for (ArcMgrDetailVO dvo:mgrList.get(i).getArcMgrDetailList()) {
				if (ArchiveConstants.DOSSOER_TEMP_3.equals(dvo.getDossierTemp())
						&&(dvo.getEleId()==null||dvo.getEleId()<1)) {
					hMap.put(dvo.getArcReceiptDetailId(),"1");
				}
		}
		}
		String contractNo=cVo.getContractNo();
		//电子档案赋值初始化
		Map<Long,List<FilSignDTO>> map=new HashMap<Long,List<FilSignDTO>>();
		//查找合同配置信息
		PrjContCfgDQC qc2=new PrjContCfgDQC();
		//qc2.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		qc2.setSysCd(CurrentThreadContext.getCurrentSysCd());
		List<PrjContCfgDDTO> cfdList=this.projectQueryApiService.searchPrjContCfgDDTOList(qc2);
		//交接单明细查询
		ArcReceiptDetailQueryCondition rdqc=new ArcReceiptDetailQueryCondition();
		rdqc.setArcReceiptMainId(cVo.getArcReceiptMainId());
		List<ArcReceiptDetailVO> arcReceiptDetailVOList = ArcReceiptDetailVOTransform.toVOList(this.arcReceiptMainService.arcReceiptDetailList(rdqc));
		//查总电子档案
		for (ArcReceiptDetailVO dVo:arcReceiptDetailVOList){			
			if (ArchiveConstants.DOSSOER_TEMP_3.equals( dVo.getType())&&"1".equals(hMap.get(dVo.getId()))) {//电子则获取电子档案id
				ArcBscInfoVO arcBscInfoVO = this.arcBscInfoService.selectById(dVo.getArcBscInfo());
				for (PrjContCfgDDTO cfg:cfdList) {
					if (arcBscInfoVO.getCfgCd()!=null&&arcBscInfoVO.getCfgDtlCd()!=null) {
						if (arcBscInfoVO.getCfgDtlCd().equals(cfg.getCfgDtlCd())
							&&arcBscInfoVO.getCfgCd().equals(cfg.getCfgCd())	
								) {
							//征信系统查询授权书RC_CST_BSC_INFO身份证号匹配
							if (ArchiveConstants.DZ_ZX.contains(cfg.getSampleUrl())) {
								PrjBscInfoQueryCondition pqc=new PrjBscInfoQueryCondition();
								pqc.setLsCntNo(contractNo);
								List<PrjBscInfoVO> plist= prjBscInfoService.searchPrjBscInfoList(pqc);
								if (plist!=null) {
									Long cstId=plist.get(0).getRcCstBscInfoId();
//									CstBscInfoVO cst=cstBscInfoService.selectById(cstId);
//									if (cst!=null) {
//										RcCstBscInfoQC qc1=new RcCstBscInfoQC();
//										qc1.setCertNo(cst.getCertNo());
//										List<RcCstBscInfoDTO> list= this.riskCtrlSearchApiService.searchRcCstBscInfoList(qc1,
//												CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
										if (cstId!=null) {
											List<FilSignDTO> fillist=new ArrayList<FilSignDTO>();
				//							for (int i = 0; i < list.size(); i++) {
												FilSignQueryCondition qc3=new FilSignQueryCondition();
												qc3.setFilId(cstId);
												//qc3.setTemplateId(cfg.getSampleUrl());
												qc3.setContractNm(cfg.getContNm());
												Pager page3=new Pager();
												page3.setCondition(qc3);
												List<FilSignDTO> list2=(List<FilSignDTO>)this.filSignApiService.searchListPage(page3).getResultList();
												if (list2!=null&&list2.size()>0) {
													for (int j = 0; j < list2.size(); j++) {
														if (StringUtils.isNotBlank(list2.get(j).getFilePath())) {
															fillist.add(list2.get(j));
														}
													}						
												}
				//							}
											if (fillist.size()>0) {
												map.put(dVo.getId(), fillist);
											}
											
										}
									//}
								}
							}else {
								//不区分支付表只区分合同,查找pdf信息
								FilSignQueryCondition qc3=new FilSignQueryCondition();
								qc3.setContractCode(contractNo);
								//qc3.setTemplateId(cfg.getSampleUrl());
								qc3.setContractNm(cfg.getContNm());
								Pager page3=new Pager();
								page3.setCondition(qc3);
								List<FilSignDTO> list2=(List<FilSignDTO>)this.filSignApiService.searchListPage(page3).getResultList();
								if (list2!=null&&list2.size()>0) {
									map.put(dVo.getId(), list2);								
								}
							}
							
							
						}
					}
					
				}
			}
		
		}
		//合同电子赋值
		for (ArcMgrDetailVO dvo:cVo.getArcMgrDetailList()) {
			if (ArchiveConstants.DOSSOER_TEMP_3.equals(dvo.getDossierTemp())) {
				if (map.get(dvo.getArcReceiptDetailId())!=null) {
					for (int j = 0; j < map.get(dvo.getArcReceiptDetailId()).size(); j++) {
						FilSignDTO filSignDTO=map.get(dvo.getArcReceiptDetailId()).get(j);
						//取最新
						if (filSignDTO.getContractCode().equals(cVo.getContractNo())
								||("-"+filSignDTO.getContractCode()).contains(("-"+cVo.getContractNo()+"-"))
								||filSignDTO.getContractNm().contains("征信")) {	
							
								dvo.setEleId(filSignDTO.getId());
								dvo.setFilePath(filSignDTO.getFilePath());
								dvo.setDossierCountT(dvo.getDossierCount());
							
						}
						if (dvo.getId()!=null) {
							this.arcMgrDetailApiService.modify(ArcMgrDetailVOTransform.toDTO(dvo));
						}
					}
					
				}
			}
		}
		//把没有归档的支付表复制一份交接单
		for (int i = 0; i < mgrList.size(); i++) {
			ArcMgrMainVO mVo=mgrList.get(i);
			
			if (mVo.getPaySchId()!=null) {	
			//支付表电子赋值
			for (int a = 0; a < mVo.getArcMgrDetailList().size();a++) {
				ArcMgrDetailVO dvo=mVo.getArcMgrDetailList().get(a);
				
				if (ArchiveConstants.DOSSOER_TEMP_3.equals(dvo.getDossierTemp())) {
					if (map.get(dvo.getArcReceiptDetailId())!=null) {
						for (int j = 0; j < map.get(dvo.getArcReceiptDetailId()).size(); j++) {
							FilSignDTO filSignDTO=map.get(dvo.getArcReceiptDetailId()).get(j);
							if (filSignDTO.getContractCode().equals(mVo.getContractNo())
									||filSignDTO.getContractCode().equals(mVo.getPaySchNo())) {							
								//取最新
									dvo.setEleId(filSignDTO.getId());
									dvo.setFilePath(filSignDTO.getFilePath());
									dvo.setDossierCountT(dvo.getDossierCount());						
							}
							if (dvo.getId()!=null) {
								this.arcMgrDetailApiService.modify(ArcMgrDetailVOTransform.toDTO(dvo));
							}
						}
						
					}
				}
			}
			}
		}
		
	}
}